<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Python 有非常丰富的第三方库可以使用，很多开发者会向 pypi 上提交自己的 Python 包。要想向 pypi 包仓库提交自己开发的包，首先要将自己的代码打包，才能上传分发。Python 打包一般用到的库是 setuptools，下面我们重点来介绍 setuptools 的配置和使用。 安装1pip install setuptools  setup.py 文件Python 库打包分发的关">
<meta name="keywords" content="Python,打包">
<meta property="og:type" content="article">
<meta property="og:title" content="Python 库打包">
<meta property="og:url" content="https://l1xnan.gitee.io/posts/201807/2748.html">
<meta property="og:site_name" content="每天进步一点点">
<meta property="og:description" content="Python 有非常丰富的第三方库可以使用，很多开发者会向 pypi 上提交自己的 Python 包。要想向 pypi 包仓库提交自己开发的包，首先要将自己的代码打包，才能上传分发。Python 打包一般用到的库是 setuptools，下面我们重点来介绍 setuptools 的配置和使用。 安装1pip install setuptools  setup.py 文件Python 库打包分发的关">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-07-19T15:44:15.845Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python 库打包">
<meta name="twitter:description" content="Python 有非常丰富的第三方库可以使用，很多开发者会向 pypi 上提交自己的 Python 包。要想向 pypi 包仓库提交自己开发的包，首先要将自己的代码打包，才能上传分发。Python 打包一般用到的库是 setuptools，下面我们重点来介绍 setuptools 的配置和使用。 安装1pip install setuptools  setup.py 文件Python 库打包分发的关">






  <link rel="canonical" href="https://l1xnan.gitee.io/posts/201807/2748.html">



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Python 库打包 | 每天进步一点点</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">每天进步一点点</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://l1xnan.gitee.io/posts/201807/2748.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="l1xnan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="每天进步一点点">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python 库打包
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-07-18 12:58:24" itemprop="dateCreated datePublished" datetime="2018-07-18T12:58:24+08:00">2018-07-18</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-07-19 23:44:15" itemprop="dateModified" datetime="2018-07-19T23:44:15+08:00">2018-07-19</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Python 有非常丰富的第三方库可以使用，很多开发者会向 pypi 上提交自己的 Python 包。要想向 pypi 包仓库提交自己开发的包，首先要将自己的代码打包，才能上传分发。Python 打包一般用到的库是 <code>setuptools</code>，下面我们重点来介绍 <code>setuptools</code> 的配置和使用。</p>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install setuptools</span><br></pre></td></tr></table></figure>

<h2 id="setup-py-文件"><a href="#setup-py-文件" class="headerlink" title="setup.py 文件"></a>setup.py 文件</h2><p>Python 库打包分发的关键在于编写 <code>setup.py</code> 文件。<code>setup.py</code> 文件编写的规则是从 <code>setuptools</code> 模块导入 setup 函数，并传入各类参数进行调用。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding:utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> setuptools <span class="keyword">import</span> setup</span><br><span class="line"></span><br><span class="line">setup(</span><br><span class="line">    name=<span class="string">'demo'</span>,     <span class="comment"># 包名字</span></span><br><span class="line">    version=<span class="string">'1.0'</span>,   <span class="comment"># 包版本</span></span><br><span class="line">    description=<span class="string">'This is a test of the setup'</span>,   <span class="comment"># 简单描述</span></span><br><span class="line">    author=<span class="string">'huoty'</span>,  <span class="comment"># 作者</span></span><br><span class="line">    author_email=<span class="string">'sudohuoty@163.com'</span>,  <span class="comment"># 作者邮箱</span></span><br><span class="line">    url=<span class="string">'https://www.konghy.com'</span>,      <span class="comment"># 包的主页</span></span><br><span class="line">    packages=[<span class="string">'demo'</span>],                 <span class="comment"># 包</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<h3 id="参数概述"><a href="#参数概述" class="headerlink" title="参数概述"></a>参数概述</h3><p>在 <code>setup()</code> 函数参数中，一部分是用来描述包的元信息；一部分用来定义了包运行的设置信息：</p>
<a id="more"></a>
<p><strong>元信息</strong></p>
<table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>name</td>
<td>包名称</td>
</tr>
<tr>
<td>version</td>
<td>包版本</td>
</tr>
<tr>
<td>author</td>
<td>程序的作者</td>
</tr>
<tr>
<td>author_email</td>
<td>程序的作者的邮箱地址</td>
</tr>
<tr>
<td>maintainer</td>
<td>维护者</td>
</tr>
<tr>
<td>maintainer_email</td>
<td>维护者的邮箱地址</td>
</tr>
<tr>
<td>url</td>
<td>程序的官网地址</td>
</tr>
<tr>
<td>license</td>
<td>程序的授权信息</td>
</tr>
<tr>
<td>description</td>
<td>程序的简单描述</td>
</tr>
<tr>
<td>long_description</td>
<td>程序的详细描述</td>
</tr>
<tr>
<td>platforms</td>
<td>程序适用的软件平台列表</td>
</tr>
<tr>
<td>classifiers</td>
<td>程序的所属分类列表</td>
</tr>
<tr>
<td>keywords</td>
<td>程序的关键字列表</td>
</tr>
<tr>
<td>download_url</td>
<td>程序的下载地址</td>
</tr>
</tbody></table>
<p><strong>设置信息</strong></p>
<table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>packages</td>
<td>需要处理的包目录(通常为包含 <code>__init__.py</code> 的文件夹)</td>
</tr>
<tr>
<td>py_modules</td>
<td>需要打包的 Python 单文件列表</td>
</tr>
<tr>
<td>cmdclass</td>
<td>添加自定义命令</td>
</tr>
<tr>
<td>package_data</td>
<td>指定包内需要包含的数据文件</td>
</tr>
<tr>
<td>include_package_data</td>
<td>自动包含包内所有受版本控制(cvs/svn/git)的数据文件</td>
</tr>
<tr>
<td>exclude_package_data</td>
<td>当 <code>include_package_data</code> 为 <code>True</code> 时该选项用于排除部分文件</td>
</tr>
<tr>
<td>data_files</td>
<td>打包时需要打包的数据文件，如图片，配置文件等</td>
</tr>
<tr>
<td>ext_modules</td>
<td>指定扩展模块</td>
</tr>
<tr>
<td>scripts</td>
<td>指定可执行脚本,安装时脚本会被安装到系统 PATH 路径下</td>
</tr>
<tr>
<td>package_dir</td>
<td>指定哪些目录下的文件被映射到哪个源码包</td>
</tr>
<tr>
<td>requires</td>
<td>指定依赖的其他包</td>
</tr>
<tr>
<td>provides</td>
<td>指定可以为哪些模块提供依赖</td>
</tr>
<tr>
<td>install_requires</td>
<td>安装时需要安装的依赖包</td>
</tr>
<tr>
<td>entry_points</td>
<td>动态发现服务和插件，下面详细讲</td>
</tr>
<tr>
<td>setup_requires</td>
<td>指定运行 setup.py 文件本身所依赖的包</td>
</tr>
<tr>
<td>dependency_links</td>
<td>指定依赖包的下载地址</td>
</tr>
<tr>
<td>extras_require</td>
<td>当前包的高级/额外特性需要依赖的分发包</td>
</tr>
<tr>
<td>zip_safe</td>
<td>不压缩包，而是以目录的形式安装</td>
</tr>
</tbody></table>
<h3 id="参数详解"><a href="#参数详解" class="headerlink" title="参数详解"></a>参数详解</h3><p>像 <code>name</code>、<code>version</code> 等定义包的元信息，这些没有什么好说的，下面我们介绍几个与代码执行相关的几个参数：</p>
<h4 id="packages-与-find-packages"><a href="#packages-与-find-packages" class="headerlink" title="packages 与 find_packages()"></a><code>packages</code> 与 <code>find_packages()</code></h4><p>定义了需要处理的包的目录，这通常为包含 <code>__init__.py</code> 的文件夹。对于简单工程来说，手动增加 <code>packages</code> 参数是容易。而对于复杂的工程来说，可能添加很多的包，这是手动添加就变得麻烦。setuptools 模块提供了一个 <code>find_packages()</code> 函数,它默认在与<code>setup.py</code> 文件同一目录下搜索各个含有 <code>__init__.py</code> 的目录做为要添加的包。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">find_packages(where=<span class="string">'.'</span>, exclude=(), include=(<span class="string">'*'</span>,))</span><br></pre></td></tr></table></figure>

<p>find_packages 函数的第一个参数用于指定在哪个目录下搜索包，参数 <code>exclude</code> 用于指定排除哪些包，参数 <code>include</code> 指出要包含的包。</p>
<p>默认默认情况下 <code>setup.py</code> 文件只在其所在的目录下搜索包。如果不用 find_packages，想要找到其他目录下的包，也可以设置 package_dir 参数，其指定哪些目录下的文件被映射到哪个源码包，如: <code>package_dir={&#39;&#39;: &#39;src&#39;}</code> 表示 “root package” 中的模块都在 <code>src</code> 目录中。</p>
<h4 id="包含数据文件"><a href="#包含数据文件" class="headerlink" title="包含数据文件"></a>包含数据文件</h4><p><strong>package_data</strong><br>该参数是一个从包名称到 glob 模式列表的字典。如果数据文件包含在包的子目录中，则 glob 可以包括子目录名称。其格式一般为 <code>{&#39;package_name&#39;: [&#39;files&#39;]}</code>，比如：<code>package_data={&#39;mypkg&#39;: [&#39;data/*.dat&#39;],}</code>。</p>
<p><strong>include_package_data</strong><br>该参数被设置为 True 时自动添加包中受版本控制的数据文件，可替代 package_data，同时，exclude_package_data 可以排除某些文件。注意当需要加入没有被版本控制的文件时，还是仍然需要使用 package_data 参数才行。</p>
<p><strong>data_files</strong><br>该参数通常用于包含不在包内的数据文件，即包的外部文件，如：配置文件，消息目录，数据文件。其指定了一系列二元组，即(目的安装目录，源文件) ，表示哪些文件被安装到哪些目录中。如果目录名是相对路径，则相对于安装前缀进行解释。</p>
<p><strong>manifest template</strong>:<br>manifest template 即编写 <code>MANIFEST.in</code> 文件，文件内容就是需要包含在分发包中的文件。一个 MANIFEST.in 文件如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">include *.txt</span><br><span class="line">recursive-include examples *.txt *.py</span><br><span class="line">prune examples/sample?/build</span><br></pre></td></tr></table></figure>

<p>MANIFEST.in 文件的编写规则可参考：<a href="https://docs.python.org/3.6/distutils/sourcedist.html" target="_blank" rel="noopener">https://docs.python.org/3.6/distutils/sourcedist.html</a></p>
<h4 id="生成脚本"><a href="#生成脚本" class="headerlink" title="生成脚本"></a>生成脚本</h4><p>有两个参数 <code>scripts</code> 参数或 <code>console_scripts</code> 可用于生成脚本。</p>
<p><code>entry_points</code> 参数用来支持自动生成脚本，其值是一个字典或者 <code>*.ini</code> 格式的字符串，从 <code>entry_point</code> 组名映射到一个表示 <code>entry_point</code> 的字符串或字符串列表，如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">setup(</span><br><span class="line">    <span class="comment"># other arguments here...</span></span><br><span class="line">    entry_points=<span class="string">"""</span></span><br><span class="line"><span class="string">        [console_scripts]: </span></span><br><span class="line"><span class="string">        foo=foo.entry:main</span></span><br><span class="line"><span class="string">        bar=foo.entry:main</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">setup(</span><br><span class="line">    <span class="comment"># other arguments here...</span></span><br><span class="line">    entry_points=&#123;</span><br><span class="line">        <span class="string">'console_scripts'</span>: [</span><br><span class="line">            <span class="string">'foo = my_package.some_module:main_func'</span>,</span><br><span class="line">            <span class="string">'bar = other_module:some_func'</span>,</span><br><span class="line">        ],</span><br><span class="line">        <span class="string">'gui_scripts'</span>: [</span><br><span class="line">            <span class="string">'baz = my_package_gui:start_func'</span>,</span><br><span class="line">        ]</span><br><span class="line">    &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p><code>scripts</code> 参数是一个列表，安装包时在该参数中列出的文件会被安装到系统 <code>PATH</code> 路径下。如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">scripts=[<span class="string">'bin/foo.sh'</span>, <span class="string">'bar.py'</span>]</span><br></pre></td></tr></table></figure>

<p>用如下方法可以将脚本重命名，例如去掉脚本文件的扩展名(.py、.sh):</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> setuptools.command.install_scripts <span class="keyword">import</span> install_scripts</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">InstallScripts</span><span class="params">(install_scripts)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        setuptools.command.install_scripts.install_scripts.run(self)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># Rename some script files</span></span><br><span class="line">        <span class="keyword">for</span> script <span class="keyword">in</span> self.get_outputs():</span><br><span class="line">            <span class="keyword">if</span> basename.endswith(<span class="string">".py"</span>) <span class="keyword">or</span> basename.endswith(<span class="string">".sh"</span>):</span><br><span class="line">                dest = script[:<span class="number">-3</span>]</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">continue</span></span><br><span class="line">            print(<span class="string">"moving %s to %s"</span> % (script, dest))</span><br><span class="line">            shutil.move(script, dest)</span><br><span class="line"></span><br><span class="line">setup(</span><br><span class="line">    <span class="comment"># other arguments here...</span></span><br><span class="line">    cmdclass=&#123;</span><br><span class="line">        <span class="string">"install_scripts"</span>: InstallScripts</span><br><span class="line">    &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p><code>其中，cmdclass</code> 参数表示自定制命令，后文详述。</p>
<h4 id="ext-modules"><a href="#ext-modules" class="headerlink" title="ext_modules"></a>ext_modules</h4><p>ext_modules 参数用于构建 C 和 C++ 扩展扩展包。其是 Extension 实例的列表，每一个 Extension 实例描述了一个独立的扩展模块，扩展模块可以设置扩展包名，头文件、源文件、链接库及其路径、宏定义和编辑参数等。如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">setup(</span><br><span class="line">    # other arguments here...</span><br><span class="line">    ext_modules=[</span><br><span class="line">        Extension(&apos;foo&apos;,</span><br><span class="line">                  glob(path.join(here, &apos;src&apos;, &apos;*.c&apos;)),</span><br><span class="line">                  libraries = [ &apos;rt&apos; ],</span><br><span class="line">                  include_dirs=[numpy.get_include()])</span><br><span class="line">    ]</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>详细了解可参考：<a href="https://docs.python.org/3.6/distutils/setupscript.html#preprocessor-options" target="_blank" rel="noopener">https://docs.python.org/3.6/distutils/setupscript.html#preprocessor-options</a></p>
<h4 id="zip-safe"><a href="#zip-safe" class="headerlink" title="zip_safe"></a>zip_safe</h4><p>zip_safe 参数决定包是否作为一个 zip 压缩后的 egg 文件安装，还是作为一个以 .egg 结尾的目录安装。因为有些工具不支持 zip 压缩文件，而且压缩后的包也不方便调试，所以建议将其设为 False，即 zip_safe=False。</p>
<h4 id="自定义命令"><a href="#自定义命令" class="headerlink" title="自定义命令"></a>自定义命令</h4><p>Setup.py 文件有很多内置的的命令，可以使用 python setup.py –help-commands 查看。如果想要定制自己需要的命令，可以添加 cmdclass 参数，其值为一个 dict。实现自定义命名需要继承 setuptools.Command 或者 distutils.core.Command 并重写 run 方法。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> setuptools <span class="keyword">import</span> setup, Command</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">InstallCommand</span><span class="params">(Command)</span>:</span></span><br><span class="line">    description = <span class="string">"Installs the foo."</span></span><br><span class="line">    user_options = [</span><br><span class="line">        (<span class="string">'foo='</span>, <span class="literal">None</span>, <span class="string">'Specify the foo to bar.'</span>),</span><br><span class="line">    ]</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">initialize_options</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.foo = <span class="literal">None</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">finalize_options</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">assert</span> self.foo <span class="keyword">in</span> (<span class="literal">None</span>, <span class="string">'myFoo'</span>, <span class="string">'myFoo2'</span>), <span class="string">'Invalid foo!'</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span><span class="params">(self)</span>:</span></span><br><span class="line">        install_all_the_things()</span><br><span class="line"></span><br><span class="line">setup(</span><br><span class="line">    ...,</span><br><span class="line">    cmdclass=&#123;</span><br><span class="line">        <span class="string">'install'</span>: InstallCommand,</span><br><span class="line">    &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>依赖关系<br>如果包依赖其他的包，可以指定 install_requires 参数，其值为一个 list，如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">install_requires=[</span><br><span class="line">    &apos;requests&gt;=1.0&apos;,</span><br><span class="line">    &apos;flask&gt;=1.0&apos;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>指定该参数后，在安装包时会自定从 pypi 仓库中下载指定的依赖包安装。</p>
<p>此外，还支持从指定链接下载依赖，即指定 dependency_links 参数，如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">dependency_links = [</span><br><span class="line">    &quot;http://packages.example.com/snapshots/foo-1.0.tar.gz&quot;,</span><br><span class="line">    &quot;http://example2.com/p/bar-1.0.tar.gz&quot;,</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>分类信息<br>classifiers 参数说明包的分类信息。所有支持的分类列表见：<a href="https://pypi.org/pypi?%3Aaction=list_classifiers" target="_blank" rel="noopener">https://pypi.org/pypi?%3Aaction=list_classifiers</a></p>
<p>示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">classifiers = [</span><br><span class="line">    <span class="comment"># 发展时期,常见的如下</span></span><br><span class="line">    <span class="comment">#   3 - Alpha</span></span><br><span class="line">    <span class="comment">#   4 - Beta</span></span><br><span class="line">    <span class="comment">#   5 - Production/Stable</span></span><br><span class="line">    <span class="string">'Development Status :: 3 - Alpha'</span>,</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 开发的目标用户</span></span><br><span class="line">    <span class="string">'Intended Audience :: Developers'</span>,</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 属于什么类型</span></span><br><span class="line">    <span class="string">'Topic :: Software Development :: Build Tools'</span>,</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 许可证信息</span></span><br><span class="line">    <span class="string">'License :: OSI Approved :: MIT License'</span>,</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 目标 Python 版本</span></span><br><span class="line">    <span class="string">'Programming Language :: Python :: 2'</span>,</span><br><span class="line">    <span class="string">'Programming Language :: Python :: 2.7'</span>,</span><br><span class="line">    <span class="string">'Programming Language :: Python :: 3'</span>,</span><br><span class="line">    <span class="string">'Programming Language :: Python :: 3.3'</span>,</span><br><span class="line">    <span class="string">'Programming Language :: Python :: 3.4'</span>,</span><br><span class="line">    <span class="string">'Programming Language :: Python :: 3.5'</span>,</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<h2 id="setup-cfg-文件"><a href="#setup-cfg-文件" class="headerlink" title="setup.cfg 文件"></a>setup.cfg 文件</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="附注"><a href="#附注" class="headerlink" title="附注"></a>附注</h2><p>可以看到，setup.py 的编写是非常麻烦的，kennethreitz 大神专门为此开了个 <a href="https://github.com/kennethreitz/setup.py" target="_blank" rel="noopener">Github: A Human’s Ultimate Guide to setup.py</a>，可以以此为模板，编写自己的 setup.py 文件。</p>
<p>参考资料：</p>
<ul>
<li><a href="https://setuptools.readthedocs.io/en/latest/" target="_blank" rel="noopener">setuptools 文档</a></li>
<li><a href="http://blog.konghy.cn/2018/04/29/setup-dot-py/" target="_blank" rel="noopener">Python 库打包分发(setup.py 编写)简易指南</a></li>
<li><a href="http://python.jobbole.com/87240/" target="_blank" rel="noopener">Python打包分发工具setuptools简介</a></li>
</ul>

      
    </div>

    

    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>l1xnan</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://l1xnan.gitee.io/posts/201807/2748.html" title="Python 库打包">https://l1xnan.gitee.io/posts/201807/2748.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/打包/" rel="tag"># 打包</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/201807/755.html" rel="next" title="Python 命令行神器 Click（三）细节">
                <i class="fa fa-chevron-left"></i> Python 命令行神器 Click（三）细节
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/201807/39716.html" rel="prev" title="MongoDB 代码片段">
                MongoDB 代码片段 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">l1xnan</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">43</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">14</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">39</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/l1xnan" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i></a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.yuque.com/l1xnan" target="_blank" title="语雀"><i class="fa fa-fw fa-crow"></i></a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-number">1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#setup-py-文件"><span class="nav-number">2.</span> <span class="nav-text">setup.py 文件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#参数概述"><span class="nav-number">2.1.</span> <span class="nav-text">参数概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数详解"><span class="nav-number">2.2.</span> <span class="nav-text">参数详解</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#packages-与-find-packages"><span class="nav-number">2.2.1.</span> <span class="nav-text">packages 与 find_packages()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#包含数据文件"><span class="nav-number">2.2.2.</span> <span class="nav-text">包含数据文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#生成脚本"><span class="nav-number">2.2.3.</span> <span class="nav-text">生成脚本</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ext-modules"><span class="nav-number">2.2.4.</span> <span class="nav-text">ext_modules</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#zip-safe"><span class="nav-number">2.2.5.</span> <span class="nav-text">zip_safe</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#自定义命令"><span class="nav-number">2.2.6.</span> <span class="nav-text">自定义命令</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#setup-cfg-文件"><span class="nav-number">3.</span> <span class="nav-text">setup.cfg 文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#附注"><span class="nav-number">4.</span> <span class="nav-text">附注</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">l1xnan</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.9.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a> v6.3.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  



	





  





  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  

  


  
  

  

  

  

  

  

</body>
</html>
